package com.peak.distribution.jms.order;

import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.peak.distribution.entity.agent.DisAgentAward;
import com.peak.distribution.entity.agent.DisAgentAwardLog;
import com.peak.distribution.entity.agent.DisAgentSales;
import com.peak.distribution.entity.goods.DisGoods;
import com.peak.distribution.entity.order.DisOrder;
import com.peak.distribution.entity.order.DisOrderGoods;
import com.peak.distribution.entity.order.DisOrderStatusLog;
import com.peak.distribution.enums.OrderStatus;
import com.peak.distribution.manager.agent.DisAgentAwardLogManager;
import com.peak.distribution.manager.agent.DisAgentAwardManager;
import com.peak.distribution.manager.agent.DisAgentSalesManager;
import com.peak.distribution.manager.order.DisOrderManager;
import com.peak.distribution.manager.order.DisOrderStatusLogManager;
import com.peak.spring.boot.core.mapper.JsonMapper;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Dates;
import com.peak.spring.boot.tools.Emptys;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单的消息处理，异步处理可以减轻主线程的压力
 * @author peak
 *
 */
@Component
@Slf4j
@Transactional
public class OrderConsumer {
	
	@Autowired
	private DisOrderManager orderManager;
	
	@Autowired
	private DisOrderStatusLogManager orderStatusLogManager;
	
	@Autowired
	private DisAgentSalesManager agentSalesManager;
	
	@Autowired
	private DisAgentAwardManager agentAwardManager;
	
	@Autowired
	private DisAgentAwardLogManager agentAwardLogManager;
	
	@Autowired
	private PasswordEncoder passwordEncoder;

	/**
	 * 修改订单状态的消息处理
	 * @param json
	 */
	@JmsListener(destination = "${mq.queue.order.change.status}")
	public void receiveChangeStatusQueue(String json) {
		log.info("接收订单状态变更消息：{}", json);
		Map<String, Object> map = JsonMapper.nonDefaultMapper().fromJson(json, HashMap.class, String.class, Object.class);
		// 获取订单id和变更的订单状态
		Integer orderId = Converts.toInteger(map.get("orderId"));
		OrderStatus status = OrderStatus.valueOf(Converts.toString(map.get("status")));
		// 更新订单状态
		DisOrder order = orderManager.getOne(orderId);
		order.setStatus(status);
		// 记录订单状态日志
		DisOrderStatusLog statusLog = new DisOrderStatusLog();
		statusLog.setOrder(order);
		statusLog.setOrderStatus(status);
		statusLog.setOrderTime(Dates.now());
		// 保存记录
		orderManager.save(order);
		orderStatusLogManager.save(statusLog);
	}
	
	/**
	 * 增加代理商和代理商团队的销量
	 * @param json
	 */
	@JmsListener(destination = "${mq.queue.order.add.up.sales}")
	public void receiveAddUpSalesQueue(String json) {
		log.info("接收订单累计销量消息：{}", json);
		// 参数获取
		Map<String, Object> map = JsonMapper.nonDefaultMapper().fromJson(json, HashMap.class, String.class, Object.class);
		Integer agentId = Converts.toInteger(map.get("agentId"));
		Integer orderId = Converts.toInteger(map.get("orderId"));
		
		// 获取订单
		DisOrder order = orderManager.getOne(orderId);
		// 获取销售记录
		DisAgentSales sales = agentSalesManager.getByAgentId(agentId);
		if (sales == null) {
			sales = new DisAgentSales();
		}
		// 只加商品的费用不算物流，只加当天的费用，其他费用每日循环统计
		sales.addSales(order.getGoodsFee());
		sales.addTotalSales(order.getGoodsFee());
		// 装逼的写法
		IntSummaryStatistics summary = order.getGoodses().stream().collect(Collectors.summarizingInt(DisOrderGoods::getQuantity));
		int sumGoods = Converts.toInt(summary.getSum());
		sales.addSalesGoods(sumGoods);
		sales.setSign(passwordEncoder.encode(sales.getSignSource()));
		// 获取团队销售记录
		List<DisAgentSales> teamSaleses = agentSalesManager.getTeamSalesByAgentId(agentId);
		if (Emptys.isNotEmpty(teamSaleses)) {
			teamSaleses.stream().forEach(p -> {
				p.addSales(order.getGoodsFee());
				p.addSalesGoods(sumGoods);
				p.addTotalSales(order.getGoodsFee());
				p.setSign(passwordEncoder.encode(p.getSignSource()));
			});
		}
		// 保存记录，增加销量
		agentSalesManager.save(sales);
		agentSalesManager.save(teamSaleses);
	}
	
	/**
	 * 给代理商返利的处理
	 * @param json
	 */
	@JmsListener(destination = "${mq.queue.order.add.up.sales}")
	public void receiveAddUpAwardQueue(String json) {
		log.info("接收订单返利消息：{}", json);
		// 参数获取
		Map<String, Object> map = JsonMapper.nonDefaultMapper().fromJson(json, HashMap.class, String.class, Object.class);
		Integer agentId = Converts.toInteger(map.get("agentId"));
		Integer orderId = Converts.toInteger(map.get("orderId"));
		
		// 获取订单
		DisOrder order = orderManager.getOne(orderId);
		// 获取返利,只有个人返利，团队的返利按月来算吧
		DisAgentAward award = agentAwardManager.getByAgentId(agentId);
		if (award == null) {
			award = new DisAgentAward();
		}
		int awardAmount = 0;
		// 暂时无阶梯价格的处理
		for (DisOrderGoods oGoods : order.getGoodses()) {
			int quantity = oGoods.getQuantity();
			DisGoods goods = oGoods.getGoods();
			Integer buyPrice = Emptys.isEmpty(goods.getBuyPrice()) ? goods.getMaxPrice() : goods.getBuyPrice();
			int differPrice = goods.getMinPrice() - buyPrice;
			awardAmount += differPrice * quantity;
		}
		// 把返利的金额加上去
		award.addAmount(awardAmount);
		award.addTotalAmount(awardAmount);
		award.setSign(passwordEncoder.encode(award.getSignSource()));
		// 创建返利的日志
		DisAgentAwardLog log = new DisAgentAwardLog();
		log.setAward(award);
		log.setAwardAmount(awardAmount);
		log.setAwardTime(Dates.now());
		log.setOrder(order);
		log.setSign(passwordEncoder.encode(log.getSignSource()));
		
		agentAwardManager.save(award);
		agentAwardLogManager.save(log);
	}
}
